/*
 * Created by Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

var popForm = 'carrerasPop.php';
var popFormPuntos = 'carrerasPopPuntos.php';
var popFormTablas = 'carrerasPopTablas.php';
var popFormItem = 'carrerasPopItem.php';
var actionForm = 'carrerasAction.php';
var action = undefined;
var actionItem = undefined;

var dataRow = undefined;
var ptoCardEditing = undefined;

var iConstPtoCard = new fn_constPtoCard();
function fn_constPtoCard()
{
	this.NORTE = "NORTE";
	this.SUR = "SUR";
	this.ESTE = "ESTE";
	this.OESTE = "OESTE";
}

var joDataCarrera;
var joDataCarreraPuntos;
var oTable;
var oTableNorte;
var oTableSur;
var oTableEste;
var oTableOeste;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var actionItemNortePK = undefined;
var aPosNorte = undefined;
var actionItemSurPK = undefined;
var aPosSur = undefined;
var actionItemEstePK = undefined;
var aPosEste = undefined;
var actionItemOestePK = undefined;
var aPosOeste = undefined;
var fechaCarrera = undefined;

function $_init()
{
	$('#btnCarreras').removeClass('btnMenu').addClass('btnMenuAct');
	
	var gaiSelected;
	
	$(document).ready(function() {
    	oTable = $('#dt_carreras').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"iDisplayLength": 50,
					"bProcessing": true,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?actionOfForm=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			{ "sWidth": "15%", "sClass": "center", "bSortable": false }
					  		]

				});
    	
    	/* Click event handler */
    	$('#dt_carreras tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		fechaCarrera = aData[2]
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	            fechaCarrera = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#carrerasDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:1040, 
		modal: true,
		position : ['center',10],
		dialogClass:'no-close',
		beforeClose: function() { $_ClearCarreraPopForm(); },
		open: function() {
			$('#carrerasDialog').css('background','url(imagenes/fondo_texto.jpg)');
			$('#btnSave').click( function(e) {
				$('#carrerasPopForm').submit();
			});
		}
	});
	
	$("#carrerasDialogPuntos").dialog({
		autoOpen:false, 
		height:330, 
		width:540, 
		modal: true,
		position : ['center',10],
		dialogClass:'no-close',
		beforeClose: function() { $_ClearCarreraPuntosPopForm(); },
		open: function() {
			$('#carrerasDialogPuntos').css('background','url(imagenes/fondo_texto.jpg)');
		}
	});
	
	$("#carrerasDialogTablas").dialog({
		autoOpen:false, 
		height:530, 
		width:1000, 
		modal: true,
		position : ['center',10],
		modal: true, 
		dialogClass:'no-close',
		open: function() {
			$('#carrerasDialogTablas').css('background','url(imagenes/fondo_texto.jpg)');
		}
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAdd").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEdit').click( function(e) {
		editProxyShow();
	});
	
	$('#btnErase').click( function(e) {
		delProxyShow();
	});
	
	$('#btnAddResult').click( function(e) {
		addTablasProxyShow();
	});
	
	$('#btnViewCalcPuntos').click( function(e) {
		puntosProxyShow();
	});
}

function $_initPopTablas()
{
	var gaiSelectedNorte;
	var gaiSelectedSur;
	var gaiSelectedEste;
	var gaiSelectedOeste;
	
	createUploader();
	
	//Add Click for All Buttons in Search Form
	$("#btnAddItemPop").click( function(e) {
		addItemProxyShow();
    });
	
	$('#btnImportTablasPop').click( function(e) {
		importDataProxyShow();
	});
	
	$('#btnCloseTablasPop').click( function(e) {
		$('#carrerasDialogTablas').dialog('close');
	});
	
	$('#btnRecalcularPop').click( function(e) {
		$_recalcularDatos();
	});
	
	//Botones para Editar el Item
	$('#btnEditNorteItemPop').click( function(e) {
		editItemProxyShow(iConstPtoCard.NORTE);
	});
	
	$('#btnEditSurItemPop').click( function(e) {
		editItemProxyShow(iConstPtoCard.SUR);
	});
	
	$('#btnEditEsteItemPop').click( function(e) {
		editItemProxyShow(iConstPtoCard.ESTE);
	});
	
	$('#btnEditOesteItemPop').click( function(e) {
		editItemProxyShow(iConstPtoCard.OESTE);
	});
	
	//Botones para Eliminar el Item
	$('#btnDeleteNorteItemPop').click( function(e) {
		delProxyShowItem(iConstPtoCard.NORTE);
	});
	
	$('#btnDeleteSurItemPop').click( function(e) {
		delProxyShowItem(iConstPtoCard.SUR);
	});
	
	$('#btnDeleteEsteItemPop').click( function(e) {
		delProxyShowItem(iConstPtoCard.ESTE);
	});
	
	$('#btnDeleteOesteItemPop').click( function(e) {
		delProxyShowItem(iConstPtoCard.OESTE);
	});
		
	$("#carrerasDialogItem").dialog({
		autoOpen:false, 
		height:530, 
		width:800, 
		modal: true,
		dialogClass:'no-close',
		beforeClose: function() { $_ClearCarreraPopItemForm(); },
		open: function() {
			$('#carrerasDialogItem').css('background','url(imagenes/fondo_texto.jpg)');
			$('#btnSaveItemPop').click( function(e) {
				$('#carrerasDialogItem').submit();
			});
		}
	});
	
	//Datatables Norte
	oTableNorte = $('#dt_carrerasNorte').dataTable( {
		"bJQueryUI": true,
		"sPaginationType": "two_button",
		"bInfo": false,
		"bLengthChange": false,
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": actionForm + "?actionOfForm=searchCarrerasItem&carreraPtoCard=N&carreraFecha=" + encodeURIComponent(fechaCarrera),
		"fnRowCallback": function( nRow, aDataItem, iDisplayIndex ) {
			if ( jQuery.inArray(aDataItem[0], gaiSelectedNorte) != -1 )
			{
		        $(nRow).addClass('row_selected');
			}
			return nRow;
		},
		"fnDrawCallback": function(oSettings, json) {
			/* Click event handler */
			$('#dt_carrerasNorte tbody tr').click( function () {
				var aDataItem = oTableNorte.fnGetData(this);
				var iId = aDataItem[0];
				actionItemNortePK = aDataItem[0];
				
				gaiSelectedNorte =  [];
				if ( $(this).hasClass('row_selected') ) {
				    $(this).removeClass('row_selected');
				    actionItemNortePK = undefined;
				    aPosNorte = undefined;
				}
				else {
					oTableNorte.$('tr.row_selected').removeClass('row_selected');
				    $(this).addClass('row_selected');
				    aPosNorte = oTableNorte.fnGetPosition(this);
				    gaiSelectedNorte[gaiSelectedNorte.length++] = iId;
				}
			});    
		},
		"aoColumns": [
		  			{"bVisible": false },
		  			null,
		  			null,
		  			null,
		  			null,
		  			null,
		  			null,
		  			null,
		  			null,
		  			null,
		  			null,
		  			null,
		  			null,		  			
		  			null
		  		]
	});
	
	//Datatables Sur
	if($('#dt_carrerasSur').length){
		oTableSur = $('#dt_carrerasSur').dataTable( {
			"bJQueryUI": true,
			"sPaginationType": "two_button",
			"bInfo": false,
			"bLengthChange": false,
			"bProcessing": true,
			"bServerSide": true,
			"sAjaxSource": actionForm + "?actionOfForm=searchCarrerasItem&carreraPtoCard=S&carreraFecha=" + encodeURIComponent(fechaCarrera),
			"fnRowCallback": function( nRow, aDataItem, iDisplayIndex ) {
				if ( jQuery.inArray(aDataItem[0], gaiSelectedSur) != -1 )
				{
			        $(nRow).addClass('row_selected');
				}
				return nRow;
			},
			"fnDrawCallback": function(oSettings, json) {
				/* Click event handler */
				$('#dt_carrerasSur tbody tr').click( function () {
					var aDataItem = oTableSur.fnGetData(this);
					var iId = aDataItem[0];
					actionItemSurPK = aDataItem[0];
					
					gaiSelectedSur =  [];
					if ( $(this).hasClass('row_selected') ) {
					    $(this).removeClass('row_selected');
					    actionItemSurPK = undefined;
					    aPosSur = undefined;
					}
					else {
						oTableSur.$('tr.row_selected').removeClass('row_selected');
					    $(this).addClass('row_selected');
					    aPosSur = oTableSur.fnGetPosition(this);
					    gaiSelectedSur[gaiSelectedSur.length++] = iId;
					}
				});    
			},
			"aoColumns": [
				  			{"bVisible": false },
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,		  			
				  			null
			  		]
		});
	}
	
	//Datatables Este
	if($('#dt_carrerasEste').length){
		oTableEste = $('#dt_carrerasEste').dataTable( {
			"bJQueryUI": true,
			"sPaginationType": "two_button",
			"bInfo": false,
			"bLengthChange": false,
			"bProcessing": true,
			"bServerSide": true,
			"sAjaxSource": actionForm + "?actionOfForm=searchCarrerasItem&carreraPtoCard=E&carreraFecha=" + encodeURIComponent(fechaCarrera),
			"fnRowCallback": function( nRow, aDataItem, iDisplayIndex ) {
				if ( jQuery.inArray(aDataItem[0], gaiSelectedEste) != -1 )
				{
			        $(nRow).addClass('row_selected');
				}
				return nRow;
			},
			"fnDrawCallback": function(oSettings, json) {
				/* Click event handler */
				$('#dt_carrerasEste tbody tr').click( function () {
					var aDataItem = oTableEste.fnGetData(this);
					var iId = aDataItem[0];
					actionItemEstePK = aDataItem[0];
					
					gaiSelectedEste =  [];
					if ( $(this).hasClass('row_selected') ) {
					    $(this).removeClass('row_selected');
					    actionItemEstePK = undefined;
					    aPosEste = undefined;
					}
					else {
						oTableEste.$('tr.row_selected').removeClass('row_selected');
					    $(this).addClass('row_selected');
					    aPosEste = oTableEste.fnGetPosition(this);
					    gaiSelectedEste[gaiSelectedEste.length++] = iId;
					}
				});
			},
			"aoColumns": [
				  			{"bVisible": false },
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,		  			
				  			null
			  		]
		});
	}
	
	//Datatables Oeste
	if($('#dt_carrerasOeste').length){
		oTableOeste = $('#dt_carrerasOeste').dataTable( {
			"bJQueryUI": true,
			"sPaginationType": "two_button",
			"bInfo": false,
			"bLengthChange": false,
			"bProcessing": true,
			"bServerSide": true,
			"sAjaxSource": actionForm + "?actionOfForm=searchCarrerasItem&carreraPtoCard=O&carreraFecha=" + encodeURIComponent(fechaCarrera),
			"fnRowCallback": function( nRow, aDataItem, iDisplayIndex ) {
				if ( jQuery.inArray(aDataItem[0], gaiSelectedOeste) != -1 )
				{
			        $(nRow).addClass('row_selected');
				}
				return nRow;
			},
			"fnDrawCallback": function(oSettings, json) {
				/* Click event handler */
				$('#dt_carrerasOeste tbody tr').click( function () {
					var aDataItem = oTableOeste.fnGetData(this);
					var iId = aDataItem[0];
					actionItemOestePK = aDataItem[0];
					
					gaiSelectedOeste =  [];
					if ( $(this).hasClass('row_selected') ) {
					    $(this).removeClass('row_selected');
					    actionItemOestePK = undefined;
					    aPosOeste = undefined;
					}
					else {
						oTableOeste.$('tr.row_selected').removeClass('row_selected');
					    $(this).addClass('row_selected');
					    aPosOeste = oTableOeste.fnGetPosition(this);
					    gaiSelectedOeste[gaiSelectedOeste.length++] = iId;
					}
				});
			},
			"aoColumns": [
				  			{"bVisible": false },
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,
				  			null,		  			
				  			null
			  		]
		});
	}
}


function editItemProxyShow(ptoCard)
{	
	switch (ptoCard) {
		case iConstPtoCard.NORTE:
			
			if(aPosNorte === undefined)
			{
				$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
				return;
			}
			
			actionItem = iConst.EDIT
			dataRow = oTableNorte.fnGetData(aPosNorte);
			ptoCardEditing = iConstPtoCard.NORTE;
			$('#carrerasDialogItem').load(popFormItem+"?idCarrera="+actionPK).dialog('open');
			break;

		case iConstPtoCard.SUR:
			
			if(aPosSur === undefined)
			{
				$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
				return;
			}
			
			actionItem = iConst.EDIT
			dataRow = oTableSur.fnGetData(aPosSur);
			ptoCardEditing = iConstPtoCard.SUR;
			$('#carrerasDialogItem').load(popFormItem+"?idCarrera="+actionPK).dialog('open');
			break;

		case iConstPtoCard.ESTE:
			
			if(aPosEste === undefined)
			{
				$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
				return;
			}
			
			actionItem = iConst.EDIT
			dataRow = oTableEste.fnGetData(aPosEste);
			ptoCardEditing = iConstPtoCard.ESTE;
			$('#carrerasDialogItem').load(popFormItem+"?idCarrera="+actionPK).dialog('open');
			break;
			
		case iConstPtoCard.OESTE:
			
			if(aPosOeste === undefined)
			{
				$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
				return;
			}
			
			actionItem = iConst.EDIT
			dataRow = oTableOeste.fnGetData(aPosOeste);
			ptoCardEditing = iConstPtoCard.OESTE;
			$('#carrerasDialogItem').load(popFormItem+"?idCarrera="+actionPK).dialog('open');
			break;

		default:
			break;
	}
}

function delProxyShowItem(ptoCardinal)
{
	actionItem = iConst.DELETEITEM;
	
	if(ptoCardinal == iConstPtoCard.NORTE)
	{
		if(actionItemNortePK === undefined)
		{
			$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
			return;
		}
		
		$("#deleteItemsNorteDialog").dialog({
			autoOpen: false, 
			width:350,
			position: 'center',
			open: function () {
				$('#deleteItemsNorteDialog').css('background','url(imagenes/fondo_texto.jpg)');
				$('#btnConfirmNorteDelete').unbind('click');
				$('#btnConfirmNorteDelete').click( function(e) {
					
					$.ajax({
			            type: 'POST',
			            url: actionForm,
			            data: 'actionOfForm=' + actionItem + '&idCarreraItem=' + actionItemNortePK + '&ptoCardinal=N',
						dataType: 'json',
			            success: function(jsonObj)
			                                {
			                                    if(jsonObj.status === 'OK'){
													$_showMessage('OK', 'OK', jsonObj.msg);
													
													//Reset State of action and IndexPK
													actionItemNortePK = undefined;
													actionItem = iConst.NEW;
													oTableNorte.fnReloadAjax();
												}
												else
													$_showMessage('ERR', 'ERROR', jsonObj.msg);
			                                    $('#deleteItemsNorteDialog').dialog('close');
			                                }
			            });
				});
				$('#btnExitNorteDelete').click( function(e) {
					$('#deleteItemsNorteDialog').dialog('close')
				})
			}
		});
		$('#deleteItemsNorteDialog').dialog('open');
	}
	else if(ptoCardinal == iConstPtoCard.SUR)
	{
		if(actionItemSurPK === undefined)
		{
			$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
			return;
		}
		
		$("#deleteItemsSurDialog").dialog({
			autoOpen: false, 
			width:350,
			position: 'center',
			open: function () {
				$('#deleteItemsSurDialog').css('background','url(imagenes/fondo_texto.jpg)');
				$('#btnConfirmSurDelete').unbind('click');
				$('#btnConfirmSurDelete').click( function(e) {
					$.ajax({
			            type: 'POST',
			            url: actionForm,
			            data: 'actionOfForm=' + actionItem + '&idCarreraItem=' + actionItemSurPK + '&ptoCardinal=S',
						dataType: 'json',
			            success: function(jsonObj)
			                                {
			                                    if(jsonObj.status === 'OK'){
													$_showMessage('OK', 'OK', jsonObj.msg);
													
													//Reset State of action and IndexPK
													actionItemSurPK = undefined;
													actionItem = iConst.NEW;
													oTableSur.fnReloadAjax();
												}
												else
													$_showMessage('ERR', 'ERROR', jsonObj.msg);
			                                    $('#deleteItemsSurDialog').dialog('close');
			                                }
			            });
				});
				$('#btnExitSurDelete').click( function(e) {
					$('#deleteItemsSurDialog').dialog('close')
				})
			}
		});
		$('#deleteItemsSurDialog').dialog('open');
	}
	else if(ptoCardinal == iConstPtoCard.ESTE)
	{
		if(actionItemEstePK === undefined)
		{
			$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
			return;
		}
		
		$("#deleteItemsEsteDialog").dialog({
			autoOpen: false, 
			width:350,
			position: 'center',
			open: function () {
				$('#deleteItemsEsteDialog').css('background','url(imagenes/fondo_texto.jpg)');
				$('#btnConfirmEsteDelete').unbind('click');
				$('#btnConfirmEsteDelete').click( function(e) {
					$.ajax({
			            type: 'POST',
			            url: actionForm,
			            data: 'actionOfForm=' + actionItem + '&idCarreraItem=' + actionItemEstePK + '&ptoCardinal=E',
						dataType: 'json',
			            success: function(jsonObj)
			                                {
			                                    if(jsonObj.status === 'OK'){
													$_showMessage('OK', 'OK', jsonObj.msg);
													
													//Reset State of action and IndexPK
													actionItemEstePK = undefined;
													actionItem = iConst.NEW;
													oTableEste.fnReloadAjax();
												}
												else
													$_showMessage('ERR', 'ERROR', jsonObj.msg);
			                                    $('#deleteItemsEsteDialog').dialog('close');
			                                }
			            });
				});
				$('#btnExitSurDelete').click( function(e) {
					$('#deleteItemsEsteDialog').dialog('close')
				})
			}
		});
		$('#deleteItemsEsteDialog').dialog('open');
	}
	else if(ptoCardinal == iConstPtoCard.OESTE)
	{
		if(actionItemOestePK === undefined)
		{
			$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
			return;
		}
		
		$("#deleteItemsOesteDialog").dialog({
			autoOpen: false, 
			width:350,
			position: 'center',
			open: function () {
				$('#deleteItemsOesteDialog').css('background','url(imagenes/fondo_texto.jpg)');
				$('#btnConfirmOesteDelete').unbind('click');
				$('#btnConfirmOesteDelete').click( function(e) {
					$.ajax({
			            type: 'POST',
			            url: actionForm,
			            data: 'actionOfForm=' + actionItem + '&idCarreraItem=' + actionItemOestePK + '&ptoCardinal=O',
						dataType: 'json',
			            success: function(jsonObj)
			                                {
			                                    if(jsonObj.status === 'OK'){
													$_showMessage('OK', 'OK', jsonObj.msg);
													
													//Reset State of action and IndexPK
													actionItemOestePK = undefined;
													actionItem = iConst.NEW;
													oTableOeste.fnReloadAjax();
												}
												else
													$_showMessage('ERR', 'ERROR', jsonObj.msg);
			                                    $('#deleteItemsOesteDialog').dialog('close');
			                                }
			            });
				});
				$('#btnExitOesteDelete').click( function(e) {
					$('#deleteItemsOesteDialog').dialog('close')
				})
			}
		});
		$('#deleteItemsOesteDialog').dialog('open');
	}	
}

function $_populatePuntosSuelta(idCombo, idPtoSuelta)
{
	if(idPtoSuelta == undefined)
		idPtoSuelta = 0;
	
	//Clear combobox
	$("#"+idCombo).html("");
		
	//Populate Combos
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'actionOfForm=getPuntosSuelta', 
	    dataType: 'json', 
	    success: function(json) {
	    	$('#'+idCombo).append($('<option>').text('...').attr('value', 0));
	        $.each(json, function(i, value) {
	        	if(value.idPtoSuelta == idPtoSuelta)
	        		$('#'+idCombo).append($('<option selected>').text(value.description).attr('value', value.idPtoSuelta));
	        	else
	        		$('#'+idCombo).append($('<option>').text(value.description).attr('value', value.idPtoSuelta));
	        });
	    }
	});
}

function $_populateKmsPuntosSuelta(idPtoSuelta, idTextKms)
{			
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'actionOfForm=getKmsPuntosSuelta&idPtoSuelta=' + idPtoSuelta, 
	    dataType: 'json', 
	    success: function(json) {
	    	$('#'+idTextKms).val(json.kms);
	    }
	});
}

function $_initPopPuntos()
{
	//Add Click for All Buttons in Pop Form
	$('#btnExit').click( function(e) {
		$('#carrerasDialogPuntos').dialog('close');
	});
		
	$('#btnCalcPuntos').click( function(e) {
		$_calcularPuntajeCarrera();
	});
	
	$("#canPalomas").numericInt();
	
	$('#carreraName').text(joDataCarreraPuntos.carreraName);
	$('#carreraFecha').text(joDataCarreraPuntos.carreraFecha);
	$('#canPalomares').text(joDataCarreraPuntos.canPalomares);
	$('#canPalomas').val(joDataCarreraPuntos.canPalomas);
}

function $_initPop()
{	
	//Add Click for All Buttons in Pop Form
	$('#btnExit').click( function(e) {
		$('#carrerasDialog').dialog('close');
	});
	
	$("#carreraFecha").mask("99/99/9999",{placeholder:" "});
	$("#carreraFecha").datepicker({changeMonth: true, changeYear: true, showOn: 'button', buttonImage: 'imagenes/calendario.png', buttonImageOnly: true, dateFormat: "dd/mm/yy"});
	
	$("#horaApertura").mask("99:99:99",{placeholder:" "});
	$("#horaCierre").mask("99:99:99",{placeholder:" "});
	$("#horaSueltaNorte").mask("99:99:99",{placeholder:" "});
	$("#horaSueltaSur").mask("99:99:99",{placeholder:" "});
	$("#horaSueltaEste").mask("99:99:99",{placeholder:" "});
	$("#horaSueltaOeste").mask("99:99:99",{placeholder:" "});
	
	$("#horaPuestaSol1").mask("99:99:99",{placeholder:" "});
	$("#horaSaleSol1").mask("99:99:99",{placeholder:" "});
	$("#horaPuestaSol2").mask("99:99:99",{placeholder:" "});
	$("#horaSaleSol2").mask("99:99:99",{placeholder:" "});
	$("#horaPuestaSol3").mask("99:99:99",{placeholder:" "});
	$("#horaSaleSol3").mask("99:99:99",{placeholder:" "});
	
	$_ValidatorSetDefaults();
	$_initPopValidator();
		
	//Populate User Data	
	if(action == iConst.EDIT)
	{
		$('#carreraName').val(joDataCarrera.carreraName);
		$('#carreraFecha').val(joDataCarrera.carreraFecha);
		$('#diaApertura').val(joDataCarrera.diaApertura);
		$('#horaApertura').val(joDataCarrera.horaApertura);
		$('#diaCierre').val(joDataCarrera.diaCierre);
		$('#horaCierre').val(joDataCarrera.horaCierre);
		$('#carreraNorte').val(joDataCarrera.carreraNorte);
		$('#kmsNorte').val(joDataCarrera.kmsNorte);
		$('#diaSueltaNorte').val(joDataCarrera.diaSueltaNorte);
		$('#horaSueltaNorte').val(joDataCarrera.horaSueltaNorte);
		$('#carreraSur').val(joDataCarrera.carreraSur);
		$('#kmsSur').val(joDataCarrera.kmsSur);
		$('#diaSueltaSur').val(joDataCarrera.diaSueltaSur);
		$('#horaSueltaSur').val(joDataCarrera.horaSueltaSur);
		$('#carreraEste').val(joDataCarrera.carreraEste);
		$('#kmsEste').val(joDataCarrera.kmsEste);
		$('#diaSueltaEste').val(joDataCarrera.diaSueltaEste);
		$('#horaSueltaEste').val(joDataCarrera.horaSueltaEste);
		$('#carreraOeste').val(joDataCarrera.carreraOeste);
		$('#kmsOeste').val(joDataCarrera.kmsOeste);
		$('#diaSueltaOeste').val(joDataCarrera.diaSueltaOeste);
		$('#horaSueltaOeste').val(joDataCarrera.horaSueltaOeste);
		
		$("#horaPuestaSol1").val(joDataCarrera.horaPuestaSol1);
		$("#horaSaleSol1").val(joDataCarrera.horaSaleSol1);
		$("#horaPuestaSol2").val(joDataCarrera.horaPuestaSol2);
		$("#horaSaleSol2").val(joDataCarrera.horaSaleSol2);
		$("#horaPuestaSol3").val(joDataCarrera.horaPuestaSol3);
		$("#horaSaleSol3").val(joDataCarrera.horaSaleSol3);
		$("#tipoCarrera option[value='"+joDataCarrera.tipoCarrera+"']").attr("selected", "selected");
		$("#tipoPalomas option[value='"+joDataCarrera.tipoPaloma+"']").attr("selected", "selected");
		$("#blockDE option[value='"+joDataCarrera.blockDE+"']").attr("selected", "selected");
		
		$_populatePuntosSuelta('carreraNorte', joDataCarrera.idPtoCarreraNorte);
		$_populatePuntosSuelta('carreraSur',  joDataCarrera.idPtoCarreraSur);
		$_populatePuntosSuelta('carreraEste',  joDataCarrera.idPtoCarreraEste);
		$_populatePuntosSuelta('carreraOeste',  joDataCarrera.idPtoCarreraOeste);
		
		$_ocultarPtas(joDataCarrera.tipoCarrera);
		
		$("#tipoCarrera").attr('disabled','disabled');
	}
	else {
		$_populatePuntosSuelta('carreraNorte');
		$_populatePuntosSuelta('carreraSur');
		$_populatePuntosSuelta('carreraEste');
		$_populatePuntosSuelta('carreraOeste');
		
		$_ocultarPtas(iConstTipoCarrera.GENERAL);
	}
	
	$('#tipoCarrera').click( function (){
		$_ocultarPtas($(this).val());
	});
	
	$('#carreraNorte').click( function(e) {
		$_populateKmsPuntosSuelta(this.value, 'kmsNorte');
	});
	$('#carreraSur').click( function(e) {
		$_populateKmsPuntosSuelta(this.value, 'kmsSur');
	});
	$('#carreraEste').click( function(e) {
		$_populateKmsPuntosSuelta(this.value, 'kmsEste');
	});
	$('#carreraOeste').click( function(e) {
		$_populateKmsPuntosSuelta(this.value, 'kmsOeste');
	});
}

function $_ocultarPtas(tipoCarrera)
{	
	switch (tipoCarrera) {
		case iConstTipoCarrera.GENERAL:
		case iConstTipoCarrera.EXTRA:
		case iConstTipoCarrera.FONDO:
			$('#row1raPta').show();
			$('#row2daPta').show();
			$('#row3raPta').show();
			$('#row4taPta').show();

			//Add Rules
			$('#carreraSur').rules("add", {required: true,minlength: 1, messages: {required: "",minlength: ""}});
			$('#horaSueltaSur').rules("add", {required: true,minlength: 1, messages: {required: "",minlength: ""}});
			$('#carreraEste').rules("add", {required: true,minlength: 1, messages: {required: "",minlength: ""}});
			$('#horaSueltaEste').rules("add", {required: true,minlength: 1, messages: {required: "",minlength: ""}});
			$('#carreraOeste').rules("add", {required: true,minlength: 1, messages: {required: "",minlength: ""}});
			$('#horaSueltaOeste').rules("add", {required: true,minlength: 1, messages: {required: "",minlength: ""}});
			break;
			
		case iConstTipoCarrera.UNA_PTA:
			$('#row1raPta').show();
			$('#row2daPta').hide();
			$('#row3raPta').hide();
			$('#row4taPta').hide();
			
			//Remove Rules
			$('#carreraSur').rules('remove');
			$('#horaSueltaSur').rules('remove');
			$('#carreraEste').rules('remove');
			$('#horaSueltaEste').rules('remove');
			$('#carreraOeste').rules('remove');
			$('#horaSueltaOeste').rules('remove');
			break;			
		}
}

function importDataProxyShow()
{
	$("#uploadCarrerasDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		modal: true,
		open: function () {
			$('#uploadCarrerasDialog').css('background','url(imagenes/fondo_texto.jpg)');
		}
	});
	$('#uploadCarrerasDialog').dialog('open');
}

function addTablasProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: "actionOfForm=" + iConst.EDIT_RESULT + "&idCarrera=" + actionPK,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						if(jsonObj.status === 'OK'){
	        						//Open Pop Dialog
	        						$('#carrerasDialogTablas').load(popFormTablas + "?idCarrera=" + actionPK).dialog('open');
        						}
        						else {
        							$_showMessage('ALERT', 'ALERTA', 'No se pueden cargar datos para esta Carrera');
        						}
        							
                            }
        });	
}

function addItemProxyShow()
{
	//Reset State of action and IndexPK
	actionItem = iConst.NEW;
	actionItemNortePK = undefined;
	aPosNorte = undefined;
	oTableNorte.$('tr.row_selected').removeClass('row_selected');
	
	if(oTableSur) {
		actionItemSurPK = undefined;
		aPosSur = undefined;
		oTableSur.$('tr.row_selected').removeClass('row_selected');
	}
	if(oTableEste) {
		actionItemEstePK = undefined;
		aPosEste = undefined;
		oTableEste.$('tr.row_selected').removeClass('row_selected');
	}
	if(aPosOeste) {
		actionItemOestePK = undefined;
		aPosOeste = undefined;
		oTableOeste.$('tr.row_selected').removeClass('row_selected');
	}
	
	$('#carrerasDialogItem').load(popFormItem+"?idCarrera="+actionPK).dialog('open');
}

function addProxyShow() 
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	fechaCarrera = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#carrerasDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "actionOfForm=" + iConst.EDIT + "&idCarrera=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataCarrera = jsonObj;
        						//Open Pop Dialog
        						$('#carrerasDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function puntosProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	var paramData =  "actionOfForm=" + iConst.VIEW_CALC_PUNTOS + "&idCarrera=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						if(!$.isEmptyObject(jsonObj)) {
	        						joDataCarreraPuntos = jsonObj;
	        						//Open Pop Dialog
	        						$('#carrerasDialogPuntos').load(popFormPuntos).dialog('open');
        						}
                            }
        });
	
return true;
}

function $_calcularPuntajeCarrera()
{
	$('#btnCalcPuntos').attr('disabled','disabled');
	
	var paramData = 'actionOfForm=calcularPuntajeCarrera' + '&idCarrera=' + actionPK + '&canPalomas=' + $('#canPalomas').val();
		
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#carrerasDialogPuntos').dialog('close');
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
            $('#btnCalcPuntos').removeAttr('disabled');
        }
    });

return true;
}

function $_saveCarrera(action)
{
	var paramData = 'actionOfForm=addOrEdit&' + $("#carrerasPopForm").serialize() + '&tipoCarrera='+ $('#tipoCarrera').val() + '&tCarreraNorte=' + $('#carreraNorte :selected').text() + '&tCarreraSur=' + $('#carreraSur :selected').text() + '&tCarreraEste=' + $('#carreraEste :selected').text() + '&tCarreraOeste=' + $('#carreraOeste :selected').text();
	
	if(action == iConst.EDIT)
		paramData += '&idCarrera=' + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#carrerasDialog').dialog('close');
				oTable.fnReloadAjax();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteCarrerasDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deleteCarrerasDialog').css('background','url(imagenes/fondo_texto.jpg)');
			$('#btnConfirmDelete').click( function(e) {
				$_del();
			});
			$('#btnExitDelete').click( function(e) {
				$('#deleteCarrerasDialog').dialog('close')
			})
		}
	});
	$('#deleteCarrerasDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'actionOfForm=' + action + '&idCarrera=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										fechaCarrera = undefined;
										action = iConst.NEW;
										oTable.fnReloadAjax();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteCarrerasDialog').dialog('close');
                                }
            });

return true;
}

function $_initPopValidator()
{
	$('#carrerasPopForm').validate({
		submitHandler: function() {
			$_saveCarrera(action);
		}, 		
		rules: {
			carreraName: {required: true,minlength: 1},
			carreraFecha: {required: true,minlength: 1},
			diaApertura: {required: true,minlength: 1},
			horaApertura: {required: true,minlength: 1},
			diaCierre: {required: true,minlength: 1},
			horaCierre: {required: true,minlength: 1},
			carreraNorte: {required: true,minlength: 1},
			horaSueltaNorte: {required: true,minlength: 1},
			carreraSur: {required: true,minlength: 1},
			horaSueltaSur: {required: true,minlength: 1},
			carreraEste: {required: true,minlength: 1},
			horaSueltaEste: {required: true,minlength: 1},
			carreraOeste: {required: true,minlength: 1},
			horaSueltaOeste: {required: true,minlength: 1},
			horaPuestaSol1: {required: true,minlength: 1},
			horaSaleSol1: {required: true,minlength: 1},
			horaPuestaSol2: {required: true,minlength: 1},
			horaSaleSol2: {required: true,minlength: 1},
			horaPuestaSol3: {required: true,minlength: 1},
			horaSaleSol3: {required: true,minlength: 1}
		},
		messages: {
			carreraName: {required: '',minlength: ''},
			carreraFecha: {required: '',minlength: ''},
			diaApertura: {required: '',minlength: ''},
			horaApertura: {required: '',minlength: ''},
			diaCierre: {required: '',minlength: ''},
			horaCierre: {required: '',minlength: ''},
			carreraNorte: {required: '',minlength: ''},
			horaSueltaNorte: {required: '',minlength: ''},
			carreraSur: {required: '',minlength: ''},
			horaSueltaSur: {required: '',minlength: ''},
			carreraEste: {required: '',minlength: ''},
			horaSueltaEste: {required: '',minlength: ''},
			carreraOeste: {required: '',minlength: ''},
			horaSueltaOeste: {required: '',minlength: ''},
			horaPuestaSol1: {required: '',minlength: ''},
			horaSaleSol1:  {required: '',minlength: ''},
			horaPuestaSol2:  {required: '',minlength: ''},
			horaSaleSol2: {required: '',minlength: ''},
			horaPuestaSol3:  {required: '',minlength: ''},
			horaSaleSol3:  {required: '',minlength: ''}
		}
	});
}

function createUploader(){            
    var uploader = new qq.FileUploader({
        element: document.getElementById('fileUpload'),
        action: 'uploadFiles.php',
        onComplete: function(id, fileName, responseJSON){
        	if(responseJSON.success)
    		{
        		var paramData = 'actionOfForm=' + iConst.UPLOAD + '&' + 'fileName=' + fileName + '&ptoCardinal=' + $('#carreraImportPtoCardinal').val() + '&idCarrera=' + actionPK + '&fechaCarrera=' + encodeURIComponent(fechaCarrera);
        		
        		$.ajax({
                    type: 'POST',
                    url: actionForm,
                    data: paramData,
        			dataType: 'json',
                    success: function(jsonObj)
                                        {
                                            if(jsonObj.status === 'OK')
                                            {
                                            	$_showMessage('OK', 'OK', jsonObj.msg);
                                				if($('#carreraImportPtoCardinal').val() == 'N')
                                					oTableNorte.fnReloadAjax();
                                				else if($('#carreraImportPtoCardinal').val() == 'S')
                                					oTableSur.fnReloadAjax();
                                				else if($('#carreraImportPtoCardinal').val() == 'E')
                                					oTableEste.fnReloadAjax();
                                				else if($('#carreraImportPtoCardinal').val() == 'O')
                                					oTableOeste.fnReloadAjax();
                                            }
        									else
        										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                        }
                    });
    		}
        	else
        		$_showMessage('ERR', 'ERROR', responseJSON.error);
        },
    });
}

function $_ClearCarreraPopForm()
{	
	$("#carrerasDialog").empty();
}

function $_ClearCarreraPopItemForm()
{	
	$("#carrerasDialogItem").empty();
}

function $_ClearCarreraPuntosPopForm()
{
	$("#carrerasDialogPuntos").empty();
}

function $_publicarResultados(idCarrera)
{
	$('#idCarrera'+idCarrera).show();
	
	var paramData = 'actionOfForm=publicarResultados&idCarrera=' + idCarrera;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK')
										$_showMessage('OK', 'OK', jsonObj.msg);
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#idCarrera'+idCarrera).hide();
                                }
            });
}

function $_recalcularDatos()
{	
	var paramData = 'actionOfForm=calItemCarrera&idCarrera=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK')
										$_showMessage('OK', 'OK', jsonObj.msg);
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                }
            });
}